package com.innovation.chengzhangriji.ui.widget;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;

public class MaterialProgressDrawable extends BitmapDrawable implements Animatable {

    private float mRotation;
    private float mOldRotation;
    private Animation mAnimation;
    private View mParent;

    public void setProgressRotation(float rotation) {
        this.mRotation = rotation;
        invalidateSelf();
    }

    public MaterialProgressDrawable(View parent, Resources resources, Bitmap bitmap) {
        super(resources, bitmap);
        mParent = parent;
        setupAnimation();
    }

    // 创建动画
    private void setupAnimation() {
        final Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                mRotation = mOldRotation - 360 * interpolatedTime;
                invalidateSelf();
            }
        };
        animation.setInterpolator(new DecelerateInterpolator());
        animation.setDuration(1000);
        animation.setRepeatMode(Animation.RESTART);
        animation.setRepeatCount(Animation.INFINITE);
        animation.setFillAfter(true);
        mAnimation = animation;
    }

    @Override
    public void draw(Canvas c) {
        final Rect bounds = getBounds();
        final int saveCount = c.save();
        c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
        super.draw(c);
        c.restoreToCount(saveCount);
    }

    @Override
    public void start() {
        mOldRotation = mRotation;
        mParent.clearAnimation();
        mAnimation.reset();
        mParent.startAnimation(mAnimation);
    }

    @Override
    public void stop() {
        mParent.clearAnimation();
        mAnimation.cancel();
        mAnimation.reset();
    }

    @Override
    public boolean isRunning() {
        return false;
    }
}
